// 测试URL提取逻辑

const testSchemas = [
  // 正常的CDN URL
  {
    name: 'CDN图片URL',
    schema: '{"componentName":"Image","props":{"src":"https://cdn.appthen.com/Fp_s_XBf9C1PhnPplQWi0Udx8cw4"}}',
    expected: ['https://cdn.appthen.com/Fp_s_XBf9C1PhnPplQWi0Udx8cw4']
  },
  // Unsplash URL（可能被截断）
  {
    name: 'Unsplash URL',
    schema: '{"componentName":"Image","props":{"src":"https://images.unsplash.com/photo-1560250097-0ea6526b2f95?auto=format&fit=crop&w=500"}}',
    expected: ['https://images.unsplash.com/photo-1560250097-0ea6526b2f95?auto=format&fit=crop&w=500']
  },
  // 复杂的URL包含特殊字符
  {
    name: '复杂URL',
    schema: '{"componentName":"Image","props":{"src":"https://cdn.appthen.com/editor/npm/test@1.0.0/lib.js?v=2"}}',
    expected: ['https://cdn.appthen.com/editor/npm/test@1.0.0/lib.js?v=2']
  },
  // 多个URL
  {
    name: '多个URL',
    schema: '{"backgroundImage":"https://cdn.appthen.com/Fp_s_XBf9C1PhnPplQWi0Udx8cw4","logo":"https://cdn.appthen.com/Fmk8IZVxeE9QYk9hKJM-D2L4Q52_"}',
    expected: [
      'https://cdn.appthen.com/Fp_s_XBf9C1PhnPplQWi0Udx8cw4',
      'https://cdn.appthen.com/Fmk8IZVxeE9QYk9hKJM-D2L4Q52_'
    ]
  }
];

function extractUrlsFromSchema(schemaString: string): string[] {
  // 使用正则表达式提取所有URL（更精确的匹配）
  const urlRegex = /https?:\/\/[^\s"'`}\]]+(?=["'\s\)}`}\]]|$)/g;
  let matches = schemaString.match(urlRegex) as string[] | null;

  // 后处理：确保URL完整性
  if (matches) {
    matches = matches.map(url => {
      // 移除可能的尾部字符
      url = url.replace(/["'}\]\)]+$/, '');

      // 对于Unsplash URL，确保完整性
      if (url.includes('unsplash.com/photo-')) {
        // 检查是否被截断，尝试找到完整URL
        const startIndex = schemaString.indexOf(url);
        if (startIndex !== -1) {
          const remainingText = schemaString.substring(startIndex);
          const fullUrlMatch = remainingText.match(/https?:\/\/[^\s"'`}\]]+/) as string[];
          if (fullUrlMatch && fullUrlMatch.length > 0) {
            url = fullUrlMatch[0].replace(/["'}\]\)]+$/, '');
          }
        }
      }

      return url;
    });
  }

  return matches || [];
}

function runTests() {
  console.log('=== URL提取测试 ===\n');

  testSchemas.forEach((testCase, index) => {
    console.log(`${index + 1}. ${testCase.name}`);
    console.log(`Schema: ${testCase.schema}`);

    const extracted = extractUrlsFromSchema(testCase.schema);
    console.log(`提取的URLs: ${JSON.stringify(extracted)}`);
    console.log(`期望的URLs: ${JSON.stringify(testCase.expected)}`);

    const isMatch = JSON.stringify(extracted.sort()) === JSON.stringify(testCase.expected.sort());
    console.log(`结果: ${isMatch ? '✅ 通过' : '❌ 失败'}`);
    console.log('');
  });

  // 测试具体的Unsplash URL问题
  console.log('=== Unsplash URL专项测试 ===');
  const unsplashSchema = '{"componentName":"Image","props":{"src":"https://images.unsplash.com/photo-1560250097-0ea6526b2f95?auto=format&fit=crop&w=500"}}';
  const unsplashUrl = extractUrlsFromSchema(unsplashSchema)[0];

  console.log(`原始Schema: ${unsplashSchema}`);
  console.log(`提取的URL: ${unsplashUrl}`);
  console.log(`URL长度: ${unsplashUrl.length}`);
  console.log(`包含完整参数: ${unsplashUrl.includes('?auto=format&fit=crop&w=500') ? '✅ 是' : '❌ 否'}`);
}

// 运行测试
if (require.main === module) {
  runTests();
}

export { extractUrlsFromSchema, runTests };